package ercahshu

import "fmt"

func findMode(root *TreeNode) []int {
	ans := make([]int, 0)
	var preNode *TreeNode
	isDuplicate := false
	var dfs func(node *TreeNode)
	dfs = func(node *TreeNode) {
		if node == nil {
			return
		}
		dfs(node.Left)
		if preNode != nil {
			if preNode.Val == node.Val {
				if !isDuplicate {
					isDuplicate = true
				} else {
					if isDuplicate {
						ans = append(ans, preNode.Val)
						isDuplicate = false
					}
				}
			}
		}
		preNode = node
		dfs(node.Right)
	}
	dfs(root)
	if isDuplicate {
		ans = append(ans, preNode.Val)
	}
	return ans
}

func duplicateWrong(root *TreeNode) *TreeNode {
	ans := make([]int, 0)
	var preNode *TreeNode
	isDuplicate := false
	var dfs func(node *TreeNode)
	dfs = func(node *TreeNode) {
		if node == nil {
			return
		}
		dfs(node.Left)
		if preNode != nil {
			fmt.Println(preNode.Val, node.Val)
			if preNode.Val == node.Val && !isDuplicate {
				isDuplicate = true
			} else if preNode.Val != node.Val && isDuplicate {
				ans = append(ans, preNode.Val)
				isDuplicate = false
			}
		}
		preNode = node
		dfs(node.Right)
	}
	dfs(root)
	return ans
}
